package net.nohaven.proj.javeau.fs.real;

import java.io.File;

import net.nohaven.proj.javeau.fs.exceptions.ConditionsNotMetException;
import net.nohaven.proj.javeau.fs.exceptions.EntityAlreadyPresentException;
import net.nohaven.proj.javeau.fs.exceptions.EntityNotFoundException;
import net.nohaven.proj.javeau.fs.exceptions.GenericIOException;
import net.nohaven.proj.javeau.fs.model.FSDirectory;
import net.nohaven.proj.javeau.fs.model.FSFileWriter;
import net.nohaven.proj.javeau.fs.model.FSItem;
import net.nohaven.proj.javeau.fs.model.Filesystem;

public class RFSFilesystem implements Filesystem {
	private RFSDirectory pwd;

	public RFSFilesystem() {
		goToRoot();
	}

	public void cd(String path) throws EntityNotFoundException {
		if ("..".equals(path))
			cdUp();
		else
			pwd = new RFSDirectory(new File(pwd.dir, path));
	}

	public void cdUp() {
		RFSDirectory parent = pwd.getParent();
		if (parent != null)
			pwd = parent;
	}

	public FSFileWriter createFile(String name)
			throws EntityAlreadyPresentException, GenericIOException {
		File nFile = new File(pwd.dir, name);
		return new RFSFileWriter(nFile);
	}

	public void delete(String name) throws ConditionsNotMetException {
		File f = new File(pwd.dir, name);
		if (!f.exists())
			return;
		if (f.isDirectory()) {
			if (!f.delete())
				throw new ConditionsNotMetException(
						"Directory deletion failed. Maybe it's not empty.");
		} else
			f.delete();
	}

	public FSItem get(String name) {
		return pwd.get(name);
	}

	public FSDirectory getPwd() {
		return pwd;
	}

	public FSItem[] ls() {
		return pwd.getContents();
	}

	public void mkDir(String name) throws EntityAlreadyPresentException {
		File nDir = new File(pwd.dir, name);
		if (nDir.exists())
			throw new EntityAlreadyPresentException(
					"Directory or file already present");
		nDir.mkdir();
	}

	public void rename(String name, String newName)
			throws EntityNotFoundException, EntityAlreadyPresentException {
		File src = new File(pwd.dir, name);

		if (!src.exists())
			throw new EntityNotFoundException("No source File.");

		File dest = new File(pwd.dir, newName);

		if (dest.exists())
			throw new EntityAlreadyPresentException("File already present.");

		src.renameTo(dest);
	}

	public void close() {
		;
	}

	public void goToRoot() {
		try {
			pwd = new RFSRoots();
		} catch (EntityNotFoundException e) {
			pwd = null; //never actually reached
		}
	}
}
